package com.haierp.controller.purchase;

import java.util.*;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.fasterxml.jackson.core.type.TypeReference;
import com.haierp.enums.GeneralStatus;
import com.haierp.mapper.TaskReceiptMapper;
import com.haierp.model.ItemSku;
import com.haierp.model.TaskDailyDetail;
import com.haierp.model.purchase.PurchaseStorage;
import com.haierp.model.purchase.PurchaseStorageDetail;
import com.haierp.model.purchase.Receipt;
import com.haierp.model.purchase.TaskPurchase;
import com.haierp.model.purchase.TaskReceipt;
import com.haierp.service.IItemSkuService;
import com.haierp.service.ISequenceUtilService;
import com.haierp.service.ITaskDailyDetailService;
import com.haierp.service.purchase.IPurchaseStorageService;
import com.haierp.service.purchase.IReceiptService;
import com.haierp.service.purchase.ITaskPurchaseService;
import com.haierp.service.purchase.ITaskReceiptService;
import com.haierp.service.purchase.impl.TaskReceiptServiceImpl;
import com.haierp.util.DateUtil;
import com.haierp.util.JsonPageResult;
import com.haierp.util.JsonResult;
import com.haierp.vo.ReceiptQueryVO;
import com.haierp.vo.TaskReceiptQueryVO;
import com.wangzhixuan.commons.base.BaseController;
import com.wangzhixuan.commons.shiro.ShiroUser;
import com.wangzhixuan.commons.utils.HaiJsonUtils;

/**
 * 采购小票相关控制器
 * @author zhulu
 *
 */
@Controller
@RequestMapping("/receipt")
public class ReceiptController extends BaseController{

	@Autowired
	private ITaskPurchaseService taskPurchaseService;
	
	@Autowired
	private ITaskDailyDetailService taskDailyDetailService;
	
	@Autowired
	private IReceiptService receiptService;
	
	@Autowired
	private IItemSkuService itemSkuService;
	
	@Autowired
	private ITaskReceiptService taskReceiptService; 
	
	@Autowired
	private IPurchaseStorageService purchaseStorageService;
	
	@Autowired
	private ISequenceUtilService sequenceUtilService;
	/**
	 * 增加流水任务
	 * @param taskPurchase
	 * @return
	 */
	@RequestMapping("/addTaskPurchase")
	@ResponseBody
	public Object addTaskPurchase(TaskPurchase  taskPurchase) {
		JsonResult<String> result = new JsonResult<>();
		//通过子任务ID check
		TaskDailyDetail taskDailyDetail=taskDailyDetailService.selectById(taskPurchase.getSubTaskId());
		if(taskDailyDetail==null){
			return result.buildIsSuccess(false).buildData("采购子任务ID错误");
		}else{
			if(taskPurchase.getQuantity()<=0){
				return result.buildIsSuccess(false).buildData("必须填写采购数量");
			}
			List<TaskPurchase>  tps= taskPurchaseService.queryTaskPurchaseBySubTask(taskPurchase.getSubTaskId());
			int total = 0;
			if(tps!=null&&!tps.isEmpty()){
				for(TaskPurchase tp:tps){
					total+=tp.getQuantity();
				}
			}
			if((total+taskPurchase.getQuantity())>taskDailyDetail.getTaskMaxCount()){
				return result.buildIsSuccess(false).buildData("采购数量超过本次任务最大值");
			}
		}
		taskPurchaseService.insert(taskPurchase);
		return result.buildIsSuccess(true);
	}
	
	
	/**
	 * 查询小票列表
	 * @param
	 * @return
	 */
	@RequestMapping("/queryReceiptList")
	@ResponseBody
	public Object queryReceiptList() {
		JsonResult<List<Receipt>> result = new JsonResult<>();
		ShiroUser shiroUser = getShiroUser();
		Long userId = shiroUser.getId();
		EntityWrapper<Receipt> entityWrapper = new EntityWrapper<>();
		entityWrapper.where("buyer_id={0}", userId);
		List<Receipt>  receipts = receiptService.selectList(entityWrapper);
		return result.buildIsSuccess(true).buildData(receipts);
	}
	
	/**
	 * 选择小票确认入库
	 * @param receiptIds
	 * @return
	 */
	@RequestMapping("/confirm")
	@ResponseBody
	public Object confirm(String receiptIds) {
		JsonResult<String> result = new JsonResult<>();
		if(receiptIds!=null){
		  String s = receiptIds.replace("&quot;", "\"");
		  List<Long> a =  HaiJsonUtils.toBean(s, new TypeReference<List<Long>>(){});
		  List<Receipt> recs  = receiptService.selectBatchIds(a);
		  Map<Long,List<TaskPurchase>> tpMaps = new HashMap<>();
		  Long buyerId = 0L;
			if (recs != null && !recs.isEmpty()) {
				for (Receipt rec : recs) {
					if(rec.getStatus()!=GeneralStatus.INIT.getCode()){
						return result.buildIsSuccess(false).buildData("小票状态错误");
					}
					buyerId = rec.getBuyerId();
					EntityWrapper<TaskPurchase> entityWrapper = new EntityWrapper();
					entityWrapper.where("receipt_id = {0} ", rec.getId());
					List<TaskPurchase> tps = taskPurchaseService.selectList(entityWrapper);
					tps.forEach(t->{ 
						if(tpMaps.containsKey(t.getSkuId())){
							tpMaps.get(t.getSkuId()).add(t);
						}else{
							List<TaskPurchase> tlist = new ArrayList<TaskPurchase>();
							tlist.add(t);
							tpMaps.put(t.getSkuId(), tlist);
						}
					});
				}
	
			}
			//生成入库单信息
			if(!tpMaps.isEmpty()){
				PurchaseStorage purStorage = new PurchaseStorage();
				purStorage.setGmtCreate(new Date());
				purStorage.setGmtModify(new Date());
				purStorage.setStoOrderNo("G"+DateUtil.formatDate(new Date(), DateUtil.DATE_PARTEN_YYMMDD)+"U"+String.format("%0"+4+"d", buyerId)+sequenceUtilService.gainPOSequence());
				List<PurchaseStorageDetail> psdList = new ArrayList<>();
				for(Long skuId:tpMaps.keySet()){
					List<TaskPurchase> tList = tpMaps.get(skuId);
					PurchaseStorageDetail psd = new PurchaseStorageDetail();
					ItemSku itemSku = itemSkuService.selectById(skuId);
					if(itemSku==null){
						return result.buildIsSuccess(false).buildData("未知的SKU:"+itemSku.getId()); 
					}
					psd.setSkuId(skuId);
					psd.setSkuCode(itemSku.getSkuCode());
					psd.setUpc(itemSku.getUpc());
					psd.setItemId(itemSku.getItemId());
					double totalPrice = 0.0d;
					int quantity = 0;
					for(TaskPurchase t:tList){
						totalPrice+=t.getQuantity()*t.getPrice();
						quantity+= t.getQuantity();
					}
					psd.setQuantity(quantity);
					psd.setTotalPrice(totalPrice);
					psd.setGmtCreate(new Date());
					psd.setGmtModify(new Date());
					psdList.add(psd);
				}
				purStorage.setPurchaseStorageDetailList(psdList);
				purchaseStorageService.putInStorage(purStorage,recs);
			}
		} 
		return result.buildIsSuccess(true);
	}
	
	@RequestMapping("/queryReceipt")
	@ResponseBody
	public Object queryReceipt(ReceiptQueryVO receiptQueryVO) {
		JsonPageResult<List<Receipt>> result = new JsonPageResult<>();
		//如果是第三方买手
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		if(roles.contains("irhbuyer")) {
			receiptQueryVO.setBuyerId(shiroUser.getId());
		}
		result = receiptService.queryReceipt(receiptQueryVO);
		return result.buildIsSuccess(true);
	}
	
	@RequestMapping("/queryTaskReceipt")
	@ResponseBody
	public Object queryTaskReceipt(TaskReceiptQueryVO taskReceiptQueryVO) {
		JsonPageResult<List<TaskReceipt>> result = new JsonPageResult<>();
		//如果是第三方买手
		ShiroUser shiroUser = this.getShiroUser();
		Set<String> roles = shiroUser.getRoles();
		if(roles.contains("irhbuyer")) {
			taskReceiptQueryVO.setBuyerId(shiroUser.getId());
		}
		result = taskReceiptService.queryTaskReceipt(taskReceiptQueryVO);
		return result.buildIsSuccess(true);
	}
	
	@RequestMapping("/queryReceiptById")
	@ResponseBody
	public Object queryReceiptById(Long receiptId) {
		JsonPageResult<Receipt> result = new JsonPageResult<>();
		Receipt receipt = receiptService.selectById(receiptId);
		return result.buildIsSuccess(true).buildData(receipt);
	}
}
